//
//  HMComposeView.swift
//  HMSlender
//
//  Created by 赵少朋赵少朋 on 2017/2/10.
//  Copyright © 2017年 ITheima. All rights reserved.
//

import UIKit
import pop

class HMComposeView: UIView {

    // 保存六个按钮的数组
    var composeButtonsArray:[HMComposeButton] = [HMComposeButton]()
    // 保存六个按钮的数组模型
    var composeModelArray: [HMComposeModel] = [HMComposeModel]()
    // 记录hmmainvc
    var target: UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func showView(target:UIViewController) -> Void {
        // 记录
        self.target = target
        // 添加composeView -> hmmainVc.view
        target.view.addSubview(self)
        // 设置6个按钮的动画
        setupComposeButtonsAnim(isUp: true)
        
    }
    
    func setupComposeButtonsAnim(isUp: Bool){
        // 默认动画使用高度临界值
        var H:CGFloat = 350
        
        // 按钮消失
        if !isUp {
            composeButtonsArray.reverse()
            H = -350
        }
        // 遍历保存按钮的数组 分别给六个按钮设置动画
        for (i, button) in composeButtonsArray.enumerated() {
            // 实例化阻尼动画对象
            let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)!
            // 设置终点位置
            anSpring.toValue = CGPoint(x: button.center.x, y: button.center.y - H)
            // 开始时间 CACurrentMediaTime() 系统绝对时间
            anSpring.beginTime = CACurrentMediaTime() + Double(i)*0.025
            //[0-20] 弹力 越大则震动幅度越大
            anSpring.springBounciness = 4
            //[0-20] 速度 越大则动画结束越快
            anSpring.springSpeed = 12
            // 给button按钮添加动画
            button.pop_add(anSpring, forKey: nil)
        }
    }
    
    /// 设置视图
    func setupUI() -> Void {
        
        //设置大小
        self.frame.size = CGSize(width: SCREENWIDTH, height: SCREENHEIGHT)
        backgroundColor = themeColor
        addSubview(bgImageView)
        addSubview(logoImageView)
        
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        logoImageView.snp_makeConstraints { (make) in
            make.top.equalTo(self).offset(100)
            make.centerX.equalTo(self)
        }
        
        crreateChildButtons()
    }
    
    func crreateChildButtons()-> Void {
        // 得到数组
        composeModelArray = loadPlist()
        
        // 抽取按钮的宽和高度
        let buttonW: CGFloat = 80
        let buttonH: CGFloat = 110
        // 计算间距
        let buttonMargin = (SCREENWIDTH - buttonW*3)/4
        
        // 遍历数组
        for (i, composeModel) in composeModelArray.enumerated() {
            // 实例化button
            let button =  HMComposeButton()
            // 设置
            button.tag = i
            // 添加点击事件
            button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
            // 设置size
            button.frame.size = CGSize(width: buttonW, height: buttonH)
            
            // 计算列和行的索引
            let colIndex = CGFloat(i%3)
            let rowIndex = CGFloat(i/3)
            // 设置x&y轴
            button.frame.origin.x = buttonMargin + colIndex*(buttonW + buttonMargin)
            button.frame.origin.y = rowIndex*(buttonH + buttonMargin) + SCREENHEIGHT
            // 设置image
            button.setImage(UIImage(named: composeModel.icon ?? ""), for: UIControlState.normal)
            button.setTitle(composeModel.title, for: UIControlState.normal)
            addSubview(button)
            // 添加六个按钮
            composeButtonsArray.append(button)
        }
        
    }
    ///屏幕点击
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        setupComposeButtonsAnim(isUp: false)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            self.removeFromSuperview()
        }
    }
    
    // 背景图
    private lazy var bgImageView:UIImageView = {
    
        let imgView = UIImageView(image: UIImage.screenIntercept()?.applyLightEffect())
        return imgView
        
    }()
    // 文字图片
    private lazy var logoImageView:UIImageView = {
    
        let imgView = UIImageView()
        imgView.image = UIImage(named: "compose_slogan")
        imgView.sizeToFit()
        return imgView
    }()
}

//MARK:- 监听按钮点击
extension HMComposeView{
    func buttonClick(btn: HMComposeButton){
        
        // 设置按钮放大和缩小动画
        UIView.animate(withDuration: 0.25, animations: {
            // 遍历6个按钮的数组
            for button in self.composeButtonsArray {
                // 透明度设置为0.2
                button.alpha = 0.2
                // 判断是否是点击的按钮
                if btn == button {
                    // 放大操作
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else {
                    // 缩小操作
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
            
        }, completion: { (_) in
            
            UIView.animate(withDuration: 0.25, animations: {
                
                // 遍历6个按钮数组
                for button in self.composeButtonsArray {
                    // 透明度设置为1
                    button.alpha = 1
                    //把所有按钮的状态恢复为原样
                    button.transform = CGAffineTransform.identity
                }
                
            }, completion: { (_) in
                
                /*
                 - 命名空间 指得的就是项目的名称
                 - 在OC中没有命名空间 也就是说所有的类可以通过字符串转class
                 - 在Swift 中 系统提供的类可以通过字符串转class
                 - 但是程序员自定义的类需要使用命名空间.自定义类名 才可以完成字符串转class
                 */
                // 点击那个按钮 模态弹出对应的控制器 -> tag (0,1,2,3,4,5)
                
                
                let model = self.composeModelArray[btn.tag]
                // 通过模型中的classname 得到对应的class
                let c = NSClassFromString(model.classname ?? "")! as! UIViewController.Type
                // 通过class 实例化一个控制器的对象
                let vc = c.init()
                // 导航控制器
                let composeNav = HMNavigationController(rootViewController: vc)
                // 模态
                self.target?.present(composeNav, animated: true, completion: {
                    // 移除当前的视图
                    self.removeFromSuperview()
                })
                
                //                if btn.tag == 0 {
                //                    let composeVc = HMComposeViewController()
                //                    let composeNav = HMNavigationController(rootViewController: composeVc)
                //                    self.target?.present(composeNav, animated: true, completion: {
                //                        // 移除当前的视图
                //                        self.removeFromSuperview()
                //                    })
                //                }else {
                //                    // 得到一个类的字符串名称
                //                    let className = "HMVVeibo23.HMComposeViewController"
                //                    print(NSClassFromString(className))
                //                    // 通过字符串得到对应的class
                //                    let c = NSClassFromString(className)! as! UIViewController.Type
                //                    // 通过class 实例化一个对象
                //                    let vc = c.init()
                //                    let composeNav = HMNavigationController(rootViewController: vc)
                //                    self.target?.present(composeNav, animated: true, completion: {
                //                        // 移除当前的视图
                //                        self.removeFromSuperview()
                //                    })
                //                }
                
            })
        })
    }
}

//MARK:- 加载plist文件
extension HMComposeView {
    
    func loadPlist() -> [HMComposeModel]{
        // 获取路径
        let file = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        // 获取plistArray
        let plistArray = NSArray(contentsOfFile: file)!
        // 通过yymodel 字典转模型
        let tempArray = NSArray.yy_modelArray(with: HMComposeModel.self, json: plistArray) as! [HMComposeModel]
        return tempArray
    }
}


